package com.sitc.administrator.application.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.sitc.administrator.application.R;
import com.sitc.administrator.application.activity.SettingsActivity;
import com.sitc.administrator.application.domain.User;
import com.sitc.administrator.application.domain.event.LoginSuccessEvent;
import com.sitc.administrator.application.util.DownloadNotificationUtil;
import com.sitc.administrator.application.util.StaticValue;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.woblog.android.downloader.DownloadService;
import cn.woblog.android.downloader.callback.DownloadListener;
import cn.woblog.android.downloader.callback.DownloadManager;
import cn.woblog.android.downloader.domain.DownloadInfo;
import cn.woblog.android.downloader.exception.DownloadException;

import static com.sitc.administrator.application.util.InstallApk.installApk;
import static com.sitc.administrator.application.util.StorageUtil.getExternalPath;
import static com.sitc.administrator.application.util.ToastUtil.showSortToast;

public class MainMeFragment extends BaseCommonFragment {

    private Integer id;
    private final Integer notificationId = 123456;
    private DownloadManager downloadManager;
    private DownloadNotificationUtil notificationUtil;
    private boolean DownloadFlag = false;

    @BindView(R.id.tv_nickname)
    TextView tv_nickname;

    @BindView(R.id.tv_description)
    TextView tv_description;

    public static MainMeFragment newInstance(int id) {

        Bundle args = new Bundle();
        args.putSerializable(StaticValue.ID, id);
        MainMeFragment fragment = new MainMeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initViews() {
        super.initViews();


    }

    @Override
    protected void initDatas() {
        super.initDatas();


        User user = new User();
        user.setNickname(TextUtils.isEmpty(sp.getUserName())? "":sp.getUserName());
        user.setDescription(TextUtils.isEmpty(sp.getDescription())? "":sp.getDescription());
        showUserInfo(user);


    }

    @Override
    protected void initListener() {
        super.initListener();
    }


    @Override
    protected void initComplete(){


    }


    @Override
    protected View getLayoutView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main_me,null);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);

        View view =  inflater.inflate(R.layout.fragment_main_me,null);
        ButterKnife.bind(this,view);

        return view;
    }


    @OnClick(R.id.ver)
    public void bt_Ver() {

        if (DownloadFlag == false){
            showCustomizeDialog();
        }else{
            showSortToast(getContext(),R.string.me_downloading);
        }
    }


    @OnClick(R.id.settings)
    public void bt_Settings() {

        startActivity(SettingsActivity.class);

    }

    @OnClick(R.id.theme_1)
    public void theme_1() {

        sp.put("__AppTheme","1");
        getMainActivity().recreate();
    }

    @OnClick(R.id.theme_2)
    public void theme_2() {

        sp.put("__AppTheme","2");
        getMainActivity().recreate();
    }

    @OnClick(R.id.theme_3)
    public void theme_3() {

        sp.put("__AppTheme","3");
        getMainActivity().recreate();
    }

    @OnClick(R.id.theme_4)
    public void theme_4() {

        sp.put("__AppTheme","4");
        getMainActivity().recreate();
    }






    public void updateApk(){


        notificationUtil = new DownloadNotificationUtil(getContext());

        //下载测试
        downloadManager = DownloadService.getDownloadManager(getContext());

        String url = "http://120.27.140.246:8081/sty_v2/appsys/downloadAPK";

        DownloadInfo downloadInfo = new DownloadInfo.Builder()
                .setUrl(url)
                .setPath(getExternalPath("app",".apk"))
                .build();

        downloadInfo.setDownloadListener(new DownloadListener(){

            @Override
            public void onStart() {

                //showSortToast(getContext(),"onStart...");

                notificationUtil.showNotification(notificationId);
                DownloadFlag =true;

            }

            @Override
            public void onWaited() {
                //showSortToast(getContext(),"onWaited...");

            }

            @Override
            public void onPaused() {
                //showSortToast(getContext(),"onPaused...");

            }

            @Override
            public void onDownloading(long progress, long size) {

                final long p = progress*100/size ;

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        notificationUtil.updateProgress(notificationId,(int)p);
                    }
                });

                //showSortToast(getContext(),"onDownloading..." +p+"%");

            }

            @Override
            public void onRemoved() {

                //showSortToast(getContext(),"onRemoved...");

            }

            @Override
            public void onDownloadSuccess() {
                showSortToast(getContext(),"Download Success! ...");
                notificationUtil.updateProgress(notificationId,100);


                //installApk(getContext(),getExternalPath("app",".apk"));

                DownloadFlag =false;
            }

            @Override
            public void onDownloadFailed(DownloadException e) {

                //Log.d("TAG",e.getMessage());
                DownloadFlag =false;
                showSortToast(getContext(),"onDownloadFailed...");

            }
        });

        downloadManager.download(downloadInfo);

    }


    public void showUserInfo(User user){

        tv_nickname.setText(user.getNickname());
        tv_description.setText(user.getDescription());
    }


    private void showCustomizeDialog() {

        AlertDialog alertDialog = new AlertDialog.Builder(getMainActivity())
                .setTitle(R.string.me_ver)
                .setMessage(R.string.me_downapp)
                .setIcon(R.drawable.ic_logo)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        updateApk();
                    }
                })

                .setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })

                .create();
        alertDialog.show();

    }




    @Override
    public void onDestroy() {
        super.onDestroy();
    }


}
